<?php
/**
 * Created by PhpStorm.
 * User: qiyu
 * Date: 2017-09-06
 * Time: 11:24
 */

namespace app\index\controller;
use app\common\model\OrderModel;
use think\Log;
use Payment\Notify\PayNotifyInterface;
use Payment\Config;
use app\common\model\PayLogModel;

class PayNotify implements PayNotifyInterface{
    public  $wx_config=[];

    public function _initialize()
    {

        $config = cache('db_config_data');

        if(!$config){
            $config = api('Config/lists');
            cache('db_config_data',$config);
        }
        config($config);

        $this->wx_config= [
            'token'             => config('wx_token'), // 填写你设定的key
            'appid'             => config('wx_appid'), // 填写高级调用功能的app id, 请在微信开发模式后台查询
            'appsecret'         => config('wx_appsecret'), // 填写高级调用功能的密钥
            'encodingaeskey'    => config('wx_encodingaeskey'), // 填写加密用的EncodingAESKey（可选，接口传输选择加密时必需）
            'mch_id'            => config('wx_mch_id'), // 微信支付，商户ID（可选）
            'partnerkey'        => config('wx_partnerkey'), // 微信支付，密钥（可选）
            'ssl_cer'           =>  config('wx_ssl_cer'), // 微信支付，证书cert的路径（可选，操作退款或打款时必需）
            'ssl_key'           =>  config('wx_ssl_key'), // 微信支付，证书key的路径（可选，操作退款或打款时必需）
            //    'cachepath'         => config('wx_appid'), // 设置SDK缓存目录（可选，默认位置在./src/Cache下，请保证写权限）
        ];
    }

    public function notifyProcess(array $data)
    {
        Log::info(var_export($data,true));

        $channel = $data['channel'];
        if ($channel === Config::ALI_CHARGE) {// 支付宝支付

        } elseif ($channel === Config::WX_CHARGE) {// 微信支付

            $act=$data['attach'];
            if($act == 'chongzhi'){
                $PayLogModel = new PayLogModel();
                $info = $PayLogModel->get($data['out_trade_no']);
                //判断订单状态 然后改变
                if($info->status == 0){
                    //给用户加钱
                    if(!db('member')->where(['id'=>$info->userid])->setInc('money',$info->money)){
                        Log::error(db('member')->getLastSql());
                    }else{
                        //改变订单状态
                        $info->save(['status'=>1]);
                        //查找用户的OPENID
                        $touser=db('oauth_member')->where(['mid'=>$info->userid])->value('openid');
                        //微信通知 用户充值成功
                        $we=new \Wechat\WechatReceive($this->wx_config);
                        $we->sendTemplateMessage([
                            'touser'=>$touser,
                            'template_id'=>'1w8OS4FiOcI_Xi3tmKj8GiTO8uzg7t5lyqCgIgXyHW4',
                            //'url'=>url('weixin/shanghu/index','',true,true),
                            'data'=>[
                                'first'=>[
                                    "value"=>"您好，您已成功进行余额充值。",
                                    "color"=>"#173177"
                                ],
                                'accountType'=>[
                                    "value"=>'充值类型',
                                    "color"=>"#173177"
                                ],
                                'account'=>[
                                    "value"=>'余额充值',
                                    "color"=>"#173177"
                                ],
                                'amount'=>[
                                    "value"=>$info->money,
                                    "color"=>"#173177"
                                ],
                                'result'=>[
                                    "value"=>'充值成功',
                                    "color"=>"#173177"
                                ],
                                'remark'=>[
                                    "value"=>"谢谢支持，如有疑问请联系客服！",
                                    "color"=>"#173177"
                                ]
                            ]
                        ]);
                    }
                }
            }else{
                $OrderModel= new OrderModel();
                $info= $OrderModel->get(['out_trade_no'=>$data['out_trade_no']]);
                if($info->pay_status == 0){
                    //改变订单状态
                    $info->save(['pay_status'=>1]);
                    //通知用户吧。
                    $touser=db('oauth_member')->where(['mid'=>$info->uid])->value('openid');
                    $we=new \Wechat\WechatReceive($this->wx_config);
                    $we->sendTemplateMessage([
                        'touser'=>$touser,
                        'template_id'=>'-ALe-DRv-DXbofUuL-z1fqPmGo3YoYUVMrSAwQf3s1I',
                        //'url'=>url('weixin/shanghu/index','',true,true),
                        'data'=>[
                            'first'=>[
                                "value"=>"你的订单已被受理，正在充值中。",
                                "color"=>"#173177"
                            ],
                            'number'=>[
                                "value"=>$info->phone,
                                "color"=>"#173177"
                            ],
                            'value'=>[
                                "value"=>$info->order_money,
                                "color"=>"#173177"
                            ],
                            'remark'=>[
                                "value"=>"支付成功后预计10分钟之内到账，充值高峰期间可能会有延时；谢谢支持，如有疑问请联系客服！",
                                "color"=>"#173177"
                            ]
                        ]
                    ]);

                    //通知管理员
                    $we->sendTemplateMessage([
                        'touser'=>config('wx_admin_inform'),
                        'template_id'=>'1w8OS4FiOcI_Xi3tmKj8GiTO8uzg7t5lyqCgIgXyHW4',
                        //'url'=>url('weixin/shanghu/index','',true,true),
                        'data'=>[
                            'first'=>[
                                "value"=>"您好，新的充值订单。",
                                "color"=>"#173177"
                            ],
                            'accountType'=>[
                                "value"=>'手机号',
                                "color"=>"#173177"
                            ],
                            'account'=>[
                                "value"=>$info->phone,
                                "color"=>"#173177"
                            ],
                            'amount'=>[
                                "value"=>$info->order_money,
                                "color"=>"#173177"
                            ],
                            'result'=>[
                                "value"=>'待充值',
                                "color"=>"#173177"
                            ],
                            'remark'=>[
                                "value"=>"谢谢支持，如有疑问请联系客服！",
                                "color"=>"#173177"
                            ]
                        ]
                    ]);
                }
            }


        } elseif ($channel === Config::CMB_CHARGE) {// 招商支付

        } elseif ($channel === Config::CMB_BIND) {// 招商签约

        } else {
            // 其它类型的通知
        }

        // 执行业务逻辑，成功后返回true
        return true;
    }
}